package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.OAMessage;
import com.rzjm.exercise.module.service.OAMessageReplayService;
import com.rzjm.exercise.module.service.OAMessageService;
import com.rzjm.exercise.sys.core.dict.annotation.DictBody;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * OA 审批
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2018-12-15 22:20:07
 */
@Controller
@RequestMapping("/module/oa")
public class OAMessageController extends BaseController {
    @Resource
    private OAMessageService oaMessageService;
    @Resource
    private OAMessageReplayService oaMessageReplayService;
    @Resource
    private UserService userService;

    @Log("查询OA审批页面")
    @GetMapping()
    @RequiresPermissions("module:oa:oa")
    String OAMessage(Model model) {
        return "module/oa/oa";
    }


    @Log("查询OA审批")
    @ResponseBody
    @DictBody
    @GetMapping("/list")
    @RequiresPermissions("module:oa:oa")
    public DataTableLayUI<OAMessage> list(DataTableLayUI<OAMessage> condition) {
        UserDO user = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String key_word = map.containsKey("search_like_keyword") ? map.get("search_like_keyword").toString() : null;
        if(map==null){
            map = new HashMap<>();
        }
        map.put("user_id",user.getUserId());
        if(StrUtil.isNotEmpty(key_word)){
            map.put("keyword",key_word);
        }
        Page<OAMessage> page = oaMessageService.getPage(condition);
        List<OAMessage> list = oaMessageService.getPageByUserId(page,map);
        DataTableLayUI<OAMessage> dt = oaMessageService.pageSearchCustom(page,list,condition);
        List<OAMessage> listD = dt.getData();
        listD.forEach(oa->{
            oa.setCurrentUserId(getUserId());
        });
        return dt;
    }

    @Log("查询OA审批回复记录列表")
    @ResponseBody
    @DictBody
    @GetMapping("/replay/list")
    @RequiresPermissions("module:oa:oa")
    public DataTableLayUI<OAMessageReplay> replayList(DataTableLayUI<OAMessageReplay> condition) {
        DataTableLayUI<OAMessageReplay> dt = oaMessageReplayService.pageSearchLayUI(condition);
        return dt;
    }


    @Log("新增企业页面")
    @GetMapping("/add")
    @RequiresPermissions("module:oa:add")
    String add(Model model) {
        OAMessage oa = new OAMessage();
        UserDO user = getUser();
        if(user.getUserType() == 0 ||user.getUserType() == 1 || user.getUserType() == 2 || user.getUserType() == 4){//当前登录的是集团用户或者是分厂管理员，可查询片区管理员
            QueryWrapper<UserDO> userQw = new QueryWrapper<>();
            if(user.getUserType() == 2 || user.getUserType() == 4){
                userQw.eq("jituan_id",user.getGroupId());
            }
            userQw.eq("user_type",3);
            List<UserDO> users = userService.list(userQw);
            model.addAttribute("users", users);
            model.addAttribute("userTypeName", "片区管理员");

        } else if(user.getUserType() == 3){//当前登录的是片区管理员，可查询分厂管理员
            QueryWrapper<UserDO> userQw = new QueryWrapper<>();
            userQw.eq("pianqu_id",user.getPianquId());
            userQw.eq("user_type",4);
            List<UserDO> users = userService.list(userQw);
            model.addAttribute("users", users);
            model.addAttribute("userTypeName", "分厂管理员");
        }
        model.addAttribute("oa", oa);
        return "module/oa/detail";
    }

    @Log("编辑OA审批页面")
    @GetMapping("/sendOrder/{id}")
    @RequiresPermissions("module:oa:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        OAMessage oAMessage = oaMessageService.getById(id);
        UserDO user = getUser();
        if(user.getUserType() == 0 ||user.getUserType() == 1 || user.getUserType() == 2 || user.getUserType() == 4){//当前登录的是集团用户或者是分厂管理员，可查询片区管理员
            QueryWrapper<UserDO> userQw = new QueryWrapper<>();
            if(user.getUserType() == 2 || user.getUserType() == 4){
                userQw.eq("jituan_id",user.getGroupId());
            }
            userQw.eq("user_type",3);
            List<UserDO> users = userService.list(userQw);
            model.addAttribute("users", users);
            model.addAttribute("userTypeName", "片区管理员");

        } else if(user.getUserType() == 3){//当前登录的是片区管理员，可查询分厂管理员
            QueryWrapper<UserDO> userQw = new QueryWrapper<>();
            userQw.eq("pianqu_id",user.getPianquId());
            userQw.eq("user_type",4);
            List<UserDO> users = userService.list(userQw);
            model.addAttribute("users", users);
            model.addAttribute("userTypeName", "分厂管理员");
        }



        model.addAttribute("oa", oAMessage);
        return "module/oa/sendOrder";
    }

    @Log("回复OA审批页面")
    @GetMapping("/replay/{id}")
    @RequiresPermissions("module:oa:edit")
    String replay(@PathVariable("id") Integer id, Model model) {
        UserDO user = getUser();
        OAMessageReplay replay = oaMessageReplayService.findById(id);
        if(replay != null){
            if(user.getUserId().intValue() == replay.getReceiveUserId().intValue()){
                if(replay.getReadState() == 0){
                    replay.setReadState(1);
                    oaMessageReplayService.updateById(replay);
                }
            }
        }
        OAMessage oAMessage = oaMessageService.getById(replay.getMessageId());

        QueryWrapper<OAMessageReplay> qw = new QueryWrapper<>();
        qw.eq("message_id",replay.getMessageId());
        //如果当前打开回复页面的人不是发送该审批的人 可以看到跟当前人员相关的下发的所有列表
        //如果是  可以看所有跟该审批相关的所有转发
        if(user.getUserId().intValue() != oAMessage.getSendUserId().intValue()){
            qw.and(wrapper ->
                    wrapper.eq("send_user_id",user.getUserId()).or().eq("receive_user_id",user.getUserId())
            );
        }
        List<OAMessageReplay> replays = oaMessageReplayService.list(qw);
        replays.forEach(replay1->{
            replay1.setCreateTimeStr(DateUtils.getTime(replay1.getCreateTime()));
            if(replay1.getReplayTime()!=null){
                replay1.setReplayTimeStr(DateUtils.getTime(replay1.getReplayTime()));
            }
        });
        model.addAttribute("oa", oAMessage);
        model.addAttribute("replay", replay);
        model.addAttribute("replays", replays);
        model.addAttribute("myUserId", user.getUserId());
        model.addAttribute("userType", user.getUserType());
        //发送者可以看到所有的回复
//        if(user.getUserId().intValue() == oAMessage.getSendUserId().intValue()) {
//            return "module/oa/replayAll";
//        }else{//回复者只能看到自己的
//            return "module/oa/replay";
//        }
        return "module/oa/replayAll";
    }
    /**
     * 保存
     */
    @Log("新增OA审批")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:oa:add")
    @Transactional
    public R save(@Valid OAMessage oaMessage) {
        try{
            UserDO userDO = getUser();
            oaMessage.setCreateTime(new Date());
            oaMessage.setSendUserId(userDO.getUserId());
            oaMessage.setSendUserName(userDO.getName());
            boolean ret = oaMessageService.save(oaMessage);
            if(ret){
                String userIds = oaMessage.getReceiveUserIds();
                String[] idArray = userIds.split(",");
                int ok_count = 0;
                for (String id : idArray){
                    OAMessageReplay replay = new OAMessageReplay();
                    replay.setMessageId(oaMessage.getId());
                    replay.setSendUserId(userDO.getUserId());
                    replay.setSendUserName(userDO.getName());
                    replay.setReceiveUserId(Integer.parseInt(id));
                    replay.setMsgType(0);
                    replay.setState(0);
                    replay.setReadState(0);
                    UserDO userReceive = userService.findById(Integer.parseInt(id));
                    if(userReceive!=null){
                        replay.setReceiveUserName(userReceive.getName());
                    }
                    replay.setCreateTime(new Date());
                    ret = oaMessageReplayService.save(replay);
                    if(ret){
                         ok_count++;
                    }
                }
                if(ok_count == idArray.length){
                    return R.ok();
                }else{
                    return R.error();
                }
            }
        }catch (TransactionException e){
            e.printStackTrace();
            throw e;
        }
        return R.error();
    }


    /**
     * 修改
     */
    @Log("更新OA审批")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:oa:edit")
    public R update(@Valid OAMessage oAMessage) {
        oaMessageService.updateById(oAMessage);
        return R.ok();
    }

    /**
     * 回复
     */
    @Log("回复OA审批")
    @ResponseBody
    @RequestMapping("/replay")
    @RequiresPermissions("module:oa:edit")
    public R update(@Valid OAMessageReplay oaMessageReplay) {
        oaMessageReplay.setReplayTime(new Date());
        oaMessageReplay.setReceiveUserId(getUserId());
        oaMessageReplay.setState(1);
        oaMessageReplayService.updateById(oaMessageReplay);
        return R.ok();
    }


    /**
     * 转达OA审批
     */
    @Log("转达OA审批")
    @ResponseBody
    @PostMapping("/sendOrderOp")
    @RequiresPermissions("module:oa:add")
    @Transactional
    public R sendOrder(@Valid OAMessage oaMessage) {
        try{
            UserDO userDO = getUser();
            String userIds = oaMessage.getReceiveUserIds();
            String[] idArray = userIds.split(",");
            int ok_count = 0;
            for (String id : idArray){
                QueryWrapper<OAMessageReplay> qw = new QueryWrapper<>();
                qw.eq("message_id",oaMessage.getId());
                qw.eq("receive_user_id",id);
                qw.last("limit 1");
                OAMessageReplay replay = oaMessageReplayService.getOne(qw);
                if(replay == null){
                    replay = new OAMessageReplay();
                    replay.setMessageId(oaMessage.getId());
                    replay.setSendUserId(userDO.getUserId());
                    replay.setSendUserName(userDO.getName());
                    replay.setReceiveUserId(Integer.parseInt(id));
                    UserDO userReceive = userService.findById(Integer.parseInt(id));
                    if(userReceive!=null){
                        replay.setReceiveUserName(userReceive.getName());
                    }
                    replay.setMsgType(1);
                    replay.setState(0);
                    replay.setReadState(0);
                    replay.setCreateTime(new Date());
                    boolean ret = oaMessageReplayService.save(replay);
                    if(ret){
                        ok_count++;
                    }
                }
            }
            if(ok_count == idArray.length){
                return R.ok();
            }else{
                return R.error();
            }
        }catch (TransactionException e){
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 删除
     */
    @Log("删除OA审批")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:oa:remove")
    @Transactional
    public R remove( Integer id) {
        try{
            Map<String,Object> map = new HashMap<>();
            map.put("message_id",id);
            boolean ret = oaMessageReplayService.removeByMap(map);
            if(ret){
                if (oaMessageService.removeById(id)) {
                    return R.ok();
                }
            }
        }catch (Exception e){

        }
        return R.error();
    }
}
